package com.laker.admin.module.sys.util;

import com.alibaba.fastjson2.JSONObject;
import com.laker.admin.framework.exception.BusinessException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author ruoyi
 */
public class FileUploadUtils
{

    private static final Logger log = LoggerFactory.getLogger(FileUploadUtils.class);


    /**
     * 根据文件路径上传到京东云oss
     * @param imageUploadPath
     * @param file
     * @return
     */
    public static Map<String, String> uploadFile(String imageUploadPath, MultipartFile file) {

        String fileName = file.getOriginalFilename();
        String responseStr =  uploadFileClient(imageUploadPath, file, fileName);

        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        if(responseStr == null || !Objects.equals(jsonObject.getString("code"), "200")){
            log.info("上传文件失败!");
            throw new BusinessException("上传文件失败!");
        }
        Map<String, String> resultMap = new HashMap<>();
        String preFilePath = jsonObject.getString("data");
        String successUrl = "https://cdnoss.sqdsj.com.cn/" + preFilePath.substring(preFilePath.indexOf("fileName=")+9, preFilePath.length());
        resultMap.put("url", successUrl);
        resultMap.put("originalFilename", fileName);
        return resultMap;
    }

    private static String uploadFileClient(String imageUploadPath, MultipartFile file, String fileName) {
        log.info("文件上传httpUrl: {}", imageUploadPath);
        String responseBody = null;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(imageUploadPath);

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置浏览器兼容模式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //设置请求的编码格式
            builder.setCharset(Consts.UTF_8);
            //添加文件及参数
            builder.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, fileName);
            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.info("文件上传失败!");
                throw new BusinessException("文件上传失败!");
            }
            responseBody = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            log.info("post请求： {}" , responseBody);
            return responseBody;
        } catch (Exception e) {
            log.info("文件上传异常：{}", e.getMessage());
            throw new BusinessException("文件上传异常");
        } finally {
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
        }
    }


}
